package com.study.traincard.slice;

import com.study.traincard.ResourceTable;
import com.study.traincard.database.Form;
import com.study.traincard.database.FormDatabase;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.data.preferences.Preferences;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.icu.text.SimpleDateFormat;


import java.text.ParseException;
import java.util.*;

public class MainAbilitySlice extends AbilitySlice {
    private static final long SEND_PERIOD = 1000L;
    String[] word_segment, sation;
    String sdate, stime, train_serial;

    private Context context;
    private MyEventHandle myEventHandle;
    private Timer timer;
    private Preferences preferences;
    private OrmContext connect;
    private final DatabaseHelper helper = new DatabaseHelper(this);
    private Date df;
    String str_trainstart;
    String str_trainstart_time;
    String str_trainend ;
    String str_trainend_time ;
    String str_trainserial ;
    String str_seatingno ;
    String str_traveller_name ;
    String str_journey_date ;
    String str_checkport;
    String str_trainclass;
    int dimension=-1;
    int dimensionNum=0;
    ComponentProvider componentProvider;

    private final Runnable runnable = new Runnable() {
        private void initHandler() {
            EventRunner runner = EventRunner.getMainEventRunner();
            if (runner == null) {
                return;
            }
            myEventHandle = new MyEventHandle(runner);
        }

        @Override
        public void run() {
            // 初始化认证对象
            initHandler();
        }
    };
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        connect = helper.getOrmContext("FormDatabase", "FormDatabase.db", FormDatabase.class);
        startTimer();

        context = getContext();
        /* 创建数据库 */
        DatabaseHelper databaseHelper = new DatabaseHelper(context);
        String filename = "traindb";
        preferences = databaseHelper.getPreferences(filename);

        Button discern = (Button) findComponentById(ResourceTable.Id_discern_button);
        Button modify = (Button) findComponentById(ResourceTable.Id_modify_button);
        Button confirm = (Button) findComponentById(ResourceTable.Id_ok_button);
        TextField trainstart = (TextField) findComponentById(ResourceTable.Id_trainstart);
        TextField trainstart_time = (TextField) findComponentById(ResourceTable.Id_trainstart_time);
        TextField trainend = (TextField) findComponentById(ResourceTable.Id_trainend);
        TextField trainend_time = (TextField) findComponentById(ResourceTable.Id_trainend_time);
        TextField trainserial = (TextField) findComponentById(ResourceTable.Id_trainserial);
        TextField seatingno = (TextField) findComponentById(ResourceTable.Id_seatingno);
        TextField traveller_name = (TextField) findComponentById(ResourceTable.Id_traveller_name);
        TextField journey_date = (TextField) findComponentById(ResourceTable.Id_journey_date);
        TextField check_port = (TextField) findComponentById(ResourceTable.Id_check_port);
        TextField trainclass = (TextField) findComponentById(ResourceTable.Id_train_class);
        TextField trainInfo = (TextField) findComponentById(ResourceTable.Id_text_train);

        //从卡片拉起则更新数据
        if (intent.hasParameter(AbilitySlice.PARAM_FORM_IDENTITY_KEY)) {
            long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, -1);
            OrmPredicates predicates = connect.where(Form.class);
            predicates.equalTo("formID", formId);
            List<Form> users = connect.query(predicates);
            if(users.size()!=1) dimensionNum=users.size();
            Form form = users.get(0);
            dimension=form.getDimension();

            trainstart.setText(preferences.getString("trainstart", ""));
            trainstart_time.setText(preferences.getString("trainstart_time", ""));
            trainend.setText(preferences.getString("trainend", ""));
            trainend_time.setText(preferences.getString("trainend_time", ""));
            trainserial.setText(preferences.getString("trainserial", ""));
            seatingno.setText(preferences.getString("seatingno", ""));
            traveller_name.setText(preferences.getString("traveller_name", ""));
            journey_date.setText(preferences.getString("journey_date", ""));
            check_port.setText(preferences.getString("check_port",""));
            trainclass.setText(preferences.getString("trainclass",""));

        }
        // 点击按钮进行分词识别
        discern.setClickedListener(component  -> {
            Text hello_world = (Text) findComponentById(ResourceTable.Id_text_helloworld);

          //  trainInfo.setText("张飞，2023年06月04日20:08开，宁波站-武汉站，G590次列车，16车7A号，一等座，成人票，票价638.0元，检票口8A，电子客票");
            String content = trainInfo.getText();

            word_segment = content.split("，|,");
            if (word_segment.length >= 5) {
                traveller_name.setText(word_segment[0]);

                sdate = word_segment[1].substring(0, word_segment[1].indexOf("日") + 1);
                stime = word_segment[1].substring(word_segment[1].indexOf("日") + 1, word_segment[1].indexOf("开"));

                journey_date.setText(sdate);
                trainstart_time.setText(stime);

                sation = word_segment[2].split("-");

                trainstart.setText(sation[0]);
                trainend.setText(sation[1]);

                train_serial = word_segment[3].substring(0, word_segment[3].indexOf("次"));
                trainserial.setText(train_serial);

                seatingno.setText(word_segment[4]);

                check_port.setText(word_segment[8]);


                hello_world.setText("识别完成，请确认出行信息是否准确");
            } else {

                hello_world.setText("识别失败，请确认拷贝信息格式");
            }
        });
        //退出
        modify.setClickedListener(v -> terminateAbility());

        //数据保存，更新服务卡片
        confirm.setClickedListener(v -> {
            str_trainstart = trainstart.getText();
            str_trainstart_time = trainstart_time.getText();
            str_trainend = trainend.getText();
            str_trainend_time = trainend_time.getText();
            str_trainserial = trainserial.getText();
            str_seatingno = seatingno.getText();
            str_traveller_name = traveller_name.getText();
            str_journey_date = journey_date.getText();
            str_checkport=check_port.getText();
            //存储数据
            try {
                preferences.putString("trainstart", str_trainstart);
                preferences.putString("trainstart_time", str_trainstart_time);
                preferences.putString("trainend", str_trainend);
                preferences.putString("trainend_time", str_trainend_time);
                preferences.putString("trainserial", str_trainserial);
                preferences.putString("seatingno", str_seatingno);
                preferences.putString("traveller_name", str_traveller_name);
                preferences.putString("journey_date", str_journey_date);
                preferences.putString("check_port",str_checkport);
                preferences.putString("trainclass",str_trainclass);

                preferences.flush();

            } catch (NumberFormatException e) {
                new ToastDialog(context).setText("数据存储出错").show();
            }

        //若果服务卡片存在则更新服务卡片
            if (intent.hasParameter(AbilitySlice.PARAM_FORM_IDENTITY_KEY)) {
                long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, -1);
                //存储数据
                try {
                    //更新数据库
                    String journeyDate = str_journey_date + str_trainstart_time;
                    SimpleDateFormat sd = new SimpleDateFormat("yyyy年MM月dd日HH:mm");
                    try {
                        df = sd.parse(journeyDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (!str_trainstart.isEmpty()) {
                        OrmPredicates predicates = connect.where(Form.class);
                        predicates.equalTo("formID", formId);
                        List<Form> users = connect.query(predicates);
                        Form form = users.get(0);
                        form.setStr_trainstart(str_trainstart);
                        form.setStr_trainstart_time(str_trainstart_time);
                        form.setStr_trainend(str_trainend);
                        form.setStr_trainend_time(str_trainend_time);
                        form.setStr_trainserial(str_trainserial);
                        form.setStr_seatingno(str_seatingno);
                        form.setStr_traveller_name(str_traveller_name);
                        form.setStr_journey_date(str_journey_date);
                        form.setStr_checkport(str_checkport);
                        form.setStr_trainclass(str_trainclass);

                        form.setJourneyDate(df);

                        connect.update(form);
                        connect.flush();
                    }

                } catch (NumberFormatException e) {
                    new ToastDialog(context).setText("数据存储出错").show();
                }
                if (dimension == 3) {
                    componentProvider = new ComponentProvider(ResourceTable.Layout_form_image_with_info_widget_2_4, this);
                    if (!str_trainstart.isEmpty()) {
                        componentProvider.setText(ResourceTable.Id_s1_trainstart, str_trainstart);
                        componentProvider.setText(ResourceTable.Id_s1_trainstart_time, str_trainstart_time);
                        componentProvider.setText(ResourceTable.Id_s1_trainend, str_trainend);
                        componentProvider.setText(ResourceTable.Id_s1_trainserial, str_trainserial);
                        componentProvider.setText(ResourceTable.Id_s1_seatingno, str_seatingno);
                        componentProvider.setText(ResourceTable.Id_s1_travellername, str_traveller_name);
                        componentProvider.setText(ResourceTable.Id_s1_journy_date, str_journey_date);
                        componentProvider.setText(ResourceTable.Id_s1_check_port, str_checkport);

                        try {
                            getAbility().updateForm(formId, componentProvider);

                        } catch (FormException e) {
                            e.printStackTrace();
                        }
                    }else{
                        new ToastDialog(context).setText("没有出行数据，请确认出行数据").show();
                    }
                }
                if(dimension==2){
                    componentProvider = new ComponentProvider(ResourceTable.Layout_form_image_with_info_widget_2_2, this);

                    componentProvider.setText(ResourceTable.Id_s2_trainstart, str_trainstart);
                    componentProvider.setText(ResourceTable.Id_s2_trainstart_time, str_trainstart_time);
                    componentProvider.setText(ResourceTable.Id_s2_trainserial, str_trainserial);
                    componentProvider.setText(ResourceTable.Id_s2_seatingno, str_seatingno);
                    componentProvider.setText(ResourceTable.Id_s2_checkport, str_checkport);

                    try {
                        getAbility().updateForm(formId, componentProvider);
                    } catch (FormException e) {
                        e.printStackTrace();
                    }
                }
                terminateAbility();
            } else {
                new ToastDialog(context).setText("请拉伸为服务卡片使用").show();
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }
    @Override
    protected void onStop() {
        timer.cancel();
    }
    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
    /**
     * Init Component
     */
    private void initComponent() {
        Calendar now = Calendar.getInstance();
        Component dateComponent = this.findComponentById(ResourceTable.Id_text_time);
        if (dateComponent instanceof Text) {
            Text dateText = (Text) dateComponent;
            SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
            String tm = dt.format(now.getTime());
            dateText.setText(tm);
        }
    }
    //计时器
    private void startTimer() {
        timer = new Timer();
        timer.schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        runnable.run();
                        myEventHandle.sendEvent(1);
                    }
                },
                0,
                SEND_PERIOD);
    }

    private class MyEventHandle extends EventHandler {
        MyEventHandle(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            int eventId = event.eventId;
            if (eventId == 1) {
                // 更新页面
                initComponent();
            }
        }
    }
}
